package com.xfly.app.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;

import com.google.gson.reflect.TypeToken;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.bean.LocalFile;
import com.ptmall.app.bean.LocalImageHelper;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.net.okhttp.BusinessResponse;
import com.ptmall.app.net.okhttp.OkHttps;
import com.ptmall.app.ui.activity.LocalAlbumActivity;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.FileUtils;
import com.ptmall.app.utils.UriUtil;
import com.ptmall.app.view.TitleBarView;
import com.xfly.app.bean.UpBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SubHtActivity extends BaseMvpActivity implements BusinessResponse, View.OnClickListener {

    Button btn;
    EditText title;
    TitleBarView title_bar;
    String id;
    String contract;
    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    private Uri takePicUri;
    private final int TAKE_PICTURE = 0x000001;
    private final int TAKE_PICTURES = 0x000002;

    private List<LocalFile> checkedItems = new ArrayList<>();
    private final int MAX_IMG_COUNT = 1;
    private String[] VIDEO_PERMISSION = {
            Manifest.permission.CAMERA,
            //Manifest.permission.RECORD_AUDIO,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};


    PopupWindow popupWindow;
    private View popView;

    UpBean mUpBean1;
    private OkHttps okHttps;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_subht);
    }

    @Override
    public void initViews() {
        okHttps = new OkHttps(this);
        okHttps.addResponseListener(this);
        id = getIntent().getStringExtra("id");
        title_bar = findViewById(R.id.title_bar);
        btn = findViewById(R.id.btn);
        title = findViewById(R.id.title);

        title_bar.setText("填写合同名称");
    }

    @Override
    public void initEvents() {
        title_bar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(title.getText().toString())) {
                    showMsg("请先填写合同名称");
                    return;
                }
                pop();
            }
        });
    }

    private void sub() {
        Map<String, String> map = new HashMap<>();
        map.put("orders_id", id);
        map.put("contract", contract);
        map.put("contract_title", title.getText().toString());
        map.put("mold", "1");
        apiDataRepository.subht(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {

                showMsg("上传成功");
                finish();
            }
        });
    }


    private void pop() {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
                popView.findViewById(R.id.btn1).setOnClickListener(this);
                popView.findViewById(R.id.btn2).setOnClickListener(this);
                popView.findViewById(R.id.btn_cancel).setOnClickListener(this);
            }
//            View view = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn1://拍照
                takePicUri = getSomeUri();
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePicUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
                popupWindow.dismiss();
                break;
            case R.id.btn2://本地相册
                Intent intent = new Intent(getContext(),
                        LocalAlbumActivity.class);
                intent.putExtra("num", MAX_IMG_COUNT - checkedItems.size());
                startActivityForResult(intent, TAKE_PICTURES);
                popupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PICTURE:
                if (resultCode == RESULT_OK) {
                    Bitmap bm = (Bitmap) data.getExtras().get("data");

                    setImageToView(bm);
                    checkedItems.clear();
                }
                break;
            case TAKE_PICTURES:
                checkedItems.addAll(LocalImageHelper.getInstance().getCheckedItems());
                LocalImageHelper.getInstance().getCheckedItems().clear();
                if (checkedItems.size() > 0) {
                    Bitmap bm = checkedItems.get(0).getBitmap();

                    setImageToView(bm);
                    checkedItems.clear();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 创建任一Uri
     *
     * @return
     */
    private Uri getSomeUri() {
        String fileName = FileUtils.SDPATH + String.valueOf(System.currentTimeMillis()) + ".jpg";
        String local = FileUtils.SDPATH;
        File folder = new File(local);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return UriUtil.getFileUri(getContext(), new File(fileName));
    }

    protected void setImageToView(Bitmap data) {

        FileUtils.saveBitmap(data, "123456");
        okHttps.postAsynFile(HttpMethods.BASE_URL + "attachment/upload", new File(FileUtils.SDPATH + "123456.JPEG"), true, 1);
    }

    @Override
    public void OnMessageResponse(int id, String jo) {
        switch (id) {
            case 1:
                mUpBean1 = okHttps.getGson().fromJson(jo, new TypeToken<UpBean>() {
                }.getType());
                contract = mUpBean1.getId();
                sub();
                break;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
